package org.hepeng.workx.spring.cloud.netflix.zuul.filter;

import com.netflix.zuul.context.RequestContext;
import org.hepeng.workx.spring.cloud.netflix.ribbon.RibbonRequestContextHolder;
import org.hepeng.workx.spring.cloud.netflix.ribbon.RibbonRequestContext;
import org.joor.Reflect;
import org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer;
import org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelper;
import org.springframework.cloud.netflix.zuul.filters.route.RibbonCommandFactory;
import org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter;
import org.springframework.cloud.netflix.zuul.util.ZuulRuntimeException;
import org.springframework.http.client.ClientHttpResponse;

import java.util.List;

/**
 * 有严重 bug 会导致请求长时间阻塞等待
 * @author he peng
 */

@Deprecated
public class RibbonCommandContextHoldRoutingFilter extends RibbonRoutingFilter {

    private Reflect selfReflect;

    public RibbonCommandContextHoldRoutingFilter(ProxyRequestHelper helper, RibbonCommandFactory<?> ribbonCommandFactory, List<RibbonRequestCustomizer> requestCustomizers) {
        super(helper, ribbonCommandFactory, requestCustomizers);
        this.selfReflect = Reflect.on(this);
    }

    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        this.helper.addIgnoredHeaders();
        try {

//            Reflect.on(this).call("buildCommandContext" , context).get();

            Object commandContext = selfReflect.call("buildCommandContext" , context).get();
            RibbonRequestContext ribbonRequestContext = RibbonRequestContext.copy(commandContext);
            RibbonRequestContextHolder.set(ribbonRequestContext);
            ClientHttpResponse response = selfReflect.call("forward" , commandContext).get();
            setResponse(response);
            return response;
        }
        catch (Exception ex) {
            throw new ZuulRuntimeException(ex);
        } finally {
            RibbonRequestContextHolder.clear();
        }
    }
}
